package qinggui.mlz.app.controller.star;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import qinggui.mlz.app.domain.FinalImageVO;
import qinggui.mlz.app.domain.ListVO;
import qinggui.mlz.app.domain.WpVO;
import qinggui.mlz.app.domain.star.StarChildVO;
import qinggui.mlz.app.domain.star.StarVO;
import qinggui.mlz.module.category.entity.Category;
import qinggui.mlz.module.category.service.CategoryService;
import qinggui.mlz.module.star.entity.Star;
import qinggui.mlz.module.star.service.StarService;
import qinggui.mlz.module.utils.Response;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestController
public class StarController {
    @Autowired
    private StarService starService;
    @Autowired
    private CategoryService categoryService;


    /**
     * 获取所有明星
     * 把前端传过来的wp，采用base64解析->json解析，拿到数据，wp为null，代表访问的是第一页，不为null时，代表访问的是第二页，且每一个wp代表
     * 上一页的数据，所以我们只需要根据wp，查出上一页的数据，然后根据上一页的数据做后续的操作就可以。操作完直接把json->base64，最后返回给前端就行。
     *
     * @param wp      包裹的参数
     * @param keyword 筛选条件，可模糊查询
     * @return PageVO<StarChildVO>
     */
    @RequestMapping("/star/list")
    public Response getAll(@RequestParam(required = false) String wp, @RequestParam(required = false) String keyword) {
        int pageSize = 3;
        Integer page = 1;
        String keyword1 = keyword;
        // 解析wp 参数,base64解码->json解析
        WpVO javaObject = null;
        if (wp != null && !wp.isEmpty()) {
            try {
                String decode = URLDecoder.decode(wp, StandardCharsets.UTF_8);
                // fastjson包下的解码
                JSONObject jsonObject = JSON.parseObject(decode);
                javaObject = jsonObject.toJavaObject(WpVO.class);
                page = javaObject.getPage();
                keyword1 = javaObject.getKeyword();
            } catch (Exception e) {
                log.error("解析wp参数失败", e);
                return new Response(4004);
            }
        }
        List<Star> list;
        try {
            list = starService.getAllLists(page, pageSize, keyword1);
        } catch (Exception e) {
            log.error("获取所有明星失败", e);
            return new Response(4004, "获取所有明星失败");
        }
        ArrayList<StarChildVO> starParentVOList = new ArrayList<>();
        // 将所有的类目信息取出来，然后遍历，放到一个map中，然后根据id，查出对应的类目名称
        List<Category> categoryList = categoryService.getAllCategory();
        if (categoryList == null || categoryList.isEmpty()) {
            return new Response(4004, "获取类目失败");
        }
        Map<Long, String> categoryMap = new HashMap<>();
        for (Category category : categoryList) {
            categoryMap.put(category.getId(), category.getCategoryName());
        }
        // 遍历集合中的每个属性并赋值给StarChildVO
        for (Star star : list) {
            String[] images = star.getImages().split("\\$");
            // 根据_截取正则表达式匹配最后的长度和宽度
            Pattern pattern = Pattern.compile("_(\\d+)x(\\d+)\\.");
            System.out.println(images[0]);
            Matcher matcher = pattern.matcher(images[0]);
            if (!matcher.find()) {
                return new Response(4004, "获取图片失败");
            }
            int height = Integer.parseInt(matcher.group(1));
            int width = Integer.parseInt(matcher.group(2));
            FinalImageVO finalImageVO = new FinalImageVO().setHeight(height).setWidth(width).setUrl(images[0])
                    .setAr((float) width / (float) height);
            // 根据集合中的id，查出对应的类目名称
            Long categoryId = star.getCategoryId();
            // 根据类目id，查询对应的类目名称
            String categoryName = categoryMap.get(categoryId);
            StarChildVO starVO = new StarChildVO().setId(star.getId())
                    .setImage(finalImageVO)
                    .setCategoryName(categoryName)
                    .setName(star.getName())
                    .setAge(star.getAge())
                    .setGender(star.getGender());
            starParentVOList.add(starVO);
        }
        // 返回一个wp
        WpVO wpVO = new WpVO().setPage(page + 1).setKeyword(keyword1);
        //给wp进行json和base64加密。
        String jsonString = JSON.toJSONString(wpVO);
        String encodeWp = URLEncoder.encode(jsonString, StandardCharsets.UTF_8);
        ListVO<StarChildVO> starChildVOListVO = new ListVO<StarChildVO>().setList(starParentVOList)
                .setIsEnd(list.size() < pageSize).setWp(encodeWp);
        return new Response<>(1001, starChildVOListVO);
    }


    /**
     * 获取明星详情
     *
     * @param id 明星id
     * @return StarVO
     */
    @RequestMapping("/star/detail")
    public Response getById(@RequestParam Long id) {
        Star star;
        try {
            star = starService.getById(id);
        } catch (Exception e) {
            return new Response(4004, "获取明星详情失败");
        }
        String description = star.getDescription();
        // 将这个描述进行json解析成java对象
        List<HashMap> descriptionList = JSON.parseArray(description, HashMap.class);
        String[] images = star.getImages().split("\\$");
        List<String> imagesList = new ArrayList<>(Arrays.asList(images));
        Category category = categoryService.getById(star.getCategoryId());
        if (category == null) {
            return new Response(4004, "获取明星详情失败");
        }
        StarVO starVO = new StarVO().setId(star.getId())
                .setImages(imagesList)
                .setCategoryName(category.getCategoryName())
                .setName(star.getName())
                .setAge(star.getAge())
                .setGender(star.getGender())
                .setScore(star.getScore())
                .setPay(star.getPay())
                .setAssist(star.getAssist())
                .setBackboard(star.getBackboard())
                .setDescription(descriptionList);
        return new Response<>(1001, starVO);
    }
}

